package com.fly.refresh.back;

import java.io.File;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * File监听器
 * 
 * @author 00fly
 * @version [版本号, 2018年7月20日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Slf4j
@Component
public class RefreshFromFile
{
    @Autowired
    ContextRefresher contextRefresher;
    
    /**
     * 开始监听
     * 
     * @see [类、类#方法、类#成员]
     */
    @PostConstruct
    public void monitorStart()
    {
        try
        {
            URL url = ResourceUtils.getURL(ResourceUtils.CLASSPATH_URL_PREFIX);
            if (ResourceUtils.isFileURL(url))
            {
                log.info("★★★★★★★★ {} isFileURL ★★★★★★★★ ", url.getPath());
                FileAlterationObserver observer = new FileAlterationObserver(url.getPath(), FileFilterUtils.suffixFileFilter(".yml"));
                observer.addListener(new FileAlterationListenerAdaptor()
                {
                    @Override
                    public void onFileChange(File file)
                    {
                        log.info("★★★★★★★★ {} changed.", file.getName());
                        contextRefresher.refresh();
                    }
                    
                    @Override
                    public void onFileCreate(File file)
                    {
                        log.info("★★★★★★★★ {} created.", file.getName());
                        contextRefresher.refresh();
                    }
                });
                long interval = TimeUnit.SECONDS.toMillis(5); // 周期5秒
                FileAlterationMonitor monitor = new FileAlterationMonitor(interval, observer);
                monitor.start();
            }
        }
        catch (Exception e)
        {
            log.error(e.getMessage(), e);
        }
    }
}